package com.caigou.modules.personal.ui.board

import android.graphics.Color
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import androidx.activity.viewModels
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.caigou.comm.base.bean.AppBackgroundInfo
import com.caigou.comm.base.bus.BusKey
import com.caigou.comm.base.bus.LiveDataBus
import com.caigou.comm.base.constants.AppConstants
import com.caigou.comm.base.constants.RouterPath
import com.caigou.comm.base.container.BaseActivity
import com.caigou.comm.base.ext.Resource
import com.caigou.comm.base.ext.levelAliasImage
import com.caigou.comm.base.ext.observe
import com.caigou.comm.base.ext.showToast
import com.caigou.comm.base.utils.ImageLoader
import com.caigou.comm.base.viewmodel.FollowViewModel
import com.caigou.comm.base.viewmodel.ReportViewModel
import com.caigou.comm.base.widget.ReportDialog
import com.caigou.comm.base.widget.SpaceItemDecoration
import com.caigou.modules.personal.R
import com.caigou.modules.personal.adapter.BoardItemAdapter
import com.caigou.modules.personal.bean.BoardBean
import com.caigou.modules.personal.bean.BoardUserInfoBean
import com.caigou.modules.personal.databinding.ActivityBoardBinding
import com.caigou.modules.personal.viewmodel.BoardViewModel
import dagger.hilt.android.AndroidEntryPoint

/**
 * @author #Suyghur.
 * Created on 2021/12/03
 */
@Route(path = RouterPath.Personal.PAGE_PERSONAL_BOARD)
@AndroidEntryPoint
class BoardActivity : BaseActivity() {

    private lateinit var binding: ActivityBoardBinding
    private val boardViewModel: BoardViewModel by viewModels()
    private val followViewModel: FollowViewModel by viewModels()
    private val reportViewModel: ReportViewModel by viewModels()

    private var page = 1
    private val limit = 10
    private var totalPage = 0

    @Autowired(name = AppConstants.USER_ID)
    lateinit var boardUserId: String

    private val mAdapter: BoardItemAdapter by lazy {
        BoardItemAdapter(this, mutableListOf())
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityBoardBinding.inflate(layoutInflater)
        setContentView(binding.root)
        containerId = binding.boardLlContainer.id
        initView()
    }

    private fun initView() {
        ARouter.getInstance().inject(this)

        binding.boardSwipeRefreshLayout.run {
            setColorSchemeColors(resources.getColor(R.color.caigou_theme_color))
            setOnRefreshListener {
                page = 1
                fetchBoardList()
            }
        }

        mAdapter.loadMoreModule.run {
            setOnLoadMoreListener {
                mAdapter.loadMoreModule.isEnableLoadMore = true
                fetchBoardList()
            }
            isAutoLoadMore = true
            isEnableLoadMoreIfNotFullPage = false
        }
        mAdapter.setOnItemClickListener { _, _, position ->
            val item = mAdapter.data[position]
            ARouter.getInstance().build(RouterPath.Personal.PAGE_PERSONAL_BOARD_DETAIL)
                .withString(AppConstants.USER_ID,item.boardUserId)
                .withInt(AppConstants.COMMENT_ID,item.id)
                .navigation()
        }
        mAdapter.setOnItemChildClickListener { _, view, position ->
            val item = mAdapter.data[position]
            when (view.id) {
                R.id.item_comment_iv_avatar -> {
                    ARouter.getInstance().build(RouterPath.Personal.PAGE_PERSONAL_PAGE)
                        .withString(AppConstants.USER_ID, item.replyUserInfoVo.userId)
                        .navigation()
                }
                R.id.item_comment_ll_reply -> {
                    ARouter.getInstance().build(RouterPath.Personal.PAGE_PERSONAL_BOARD_DETAIL)
                        .withString(AppConstants.USER_ID,item.boardUserId)
                        .withInt(AppConstants.COMMENT_ID,item.id)
                        .navigation()
                }
                R.id.item_comment_btn_reply -> {
                    if (AppBackgroundInfo.instance.hasLogin) {
                        ARouter.getInstance()
                            .build(RouterPath.Personal.PAGE_PERSONAL_COMMENT_REPLY)
                            .withBoolean(AppConstants.SUB_REPLY, false)
                            .withObject(AppConstants.COMMENT_ITEM_BEAN, item)
                            .navigation()
                    } else {
                        ARouter.getInstance().build(RouterPath.Login.PAGE_LOGIN).navigation()
                    }
                }
                R.id.item_comment_iv_report -> {
                    if (AppBackgroundInfo.instance.hasLogin) {
                        with(ReportDialog(this)) {
                            btnConfirm.setOnClickListener {
                                if (TextUtils.isEmpty(reportCause)) {
                                    showToast("举报原因不能为空！")
                                    return@setOnClickListener
                                }
                                reportViewModel.setPostReport(
                                    AppBackgroundInfo.instance.userBean!!.userId, item.replyUserInfoVo.userId,
                                    reportCause, item.id, 1
                                )
                                dismiss()
                            }
                            show()
                        }
                    } else {
                        ARouter.getInstance().build(RouterPath.Login.PAGE_LOGIN).navigation()
                    }
                }
            }
        }

        binding.boardRecyclerView.run {
            layoutManager = LinearLayoutManager(this@BoardActivity)
            adapter = mAdapter
            itemAnimator = DefaultItemAnimator()
            addItemDecoration(SpaceItemDecoration(this@BoardActivity))
        }

        binding.boardLayoutHeader.headerBtnFollow.run {
            visibility = if (AppBackgroundInfo.instance.hasLogin and (boardUserId == AppBackgroundInfo.instance.userBean!!.userId)) {
                View.GONE
            } else {
                View.VISIBLE
            }
            setOnClickListener {
                if (AppBackgroundInfo.instance.hasLogin) {
                    followViewModel.setFollow(AppBackgroundInfo.instance.userBean!!.userId, boardUserId)
                } else {
                    ARouter.getInstance().build(RouterPath.Login.PAGE_LOGIN).navigation()
                }
            }
        }

        binding.boardBtnReply.setOnClickListener {
            if (AppBackgroundInfo.instance.hasLogin) {
                ARouter.getInstance()
                    .build(RouterPath.Personal.PAGE_PERSONAL_BOARD_REPLY)
                    .withString(AppConstants.COMMENT_ITEM_BEAN, boardUserId)
                    .navigation()
            } else {
                showToast("请您先登录")
            }
        }

        binding.boardTvBack.setOnClickListener {
            finish()
        }

        LiveDataBus.get().with(BusKey.REPLY_SUCCESS, Any::class.java).observe(this) {
            page = 1
            fetchBoardList()
        }

        fetchBoardList()
    }

    override fun observeViewModel() {
        observe(boardViewModel.boardListLiveData, ::handleGetBoardList)
        observe(followViewModel.followLiveData, ::handleSetFollow)
        observe(reportViewModel.replyReportLiveData, ::handleSetReport)
    }

    private fun handleGetBoardList(result: Resource<BoardBean>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                binding.boardSwipeRefreshLayout.isRefreshing = false
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("获取评论信息异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                binding.boardSwipeRefreshLayout.isRefreshing = false
                mAdapter.loadMoreModule.isEnableLoadMore = true

                if (result.data == null) {
                    binding.boardLlEmpty.visibility = View.VISIBLE
                    binding.boardRecyclerView.visibility = View.GONE
                    return
                }
                if (result.data!!.page.list.isNullOrEmpty()) {
                    binding.boardLlEmpty.visibility = View.VISIBLE
                    binding.boardRecyclerView.visibility = View.GONE
                } else {
                    binding.boardLlEmpty.visibility = View.GONE
                    binding.boardRecyclerView.visibility = View.VISIBLE
                }

                totalPage = result.data!!.page.totalPage

                if (page == 1) {
                    mAdapter.setList(result.data!!.page.list)
                } else {
                    mAdapter.addData(result.data!!.page.list)
                }

                if (result.data!!.page.pageSize < limit) {
                    mAdapter.loadMoreModule.loadMoreEnd(false)
                } else {
                    mAdapter.loadMoreModule.loadMoreComplete()
                }

                if (page >= totalPage) {
                    mAdapter.loadMoreModule.loadMoreEnd(false)
                } else {
                    page++
                }

                handleBoardUserUI(result.data!!.boardUserInfoVo)
            }
        }
    }

    private fun handleSetFollow(result: Resource<String>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("关注失败，请稍后再试")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                if (result.data != null) {
                    showToast(result.data!!)
                }
                fetchBoardList()
            }
        }
    }


    private fun handleSetReport(result: Resource<String>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("举报异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                if (result.data == null) {
                    return
                }
                showToast(result.data!!)
            }
        }
    }

    private fun handleBoardUserUI(bean: BoardUserInfoBean) {
        binding.boardLayoutHeader.run {
            if (TextUtils.isEmpty(bean.headImg)) {
                headerIvAvatar.setImageResource(R.drawable.img_comm_avatar)
            } else {
                ImageLoader.loadCircle(this@BoardActivity, bean.headImg, headerIvAvatar)
            }

            headerIvLevel.setImageResource(levelAliasImage(bean.level))
            headerTvNickname.text = bean.nickName
            headerTvSignature.text = if (TextUtils.isEmpty(bean.signature)) {
                "这家伙很懒，他什么也没说"
            } else {
                bean.signature
            }
            if (bean.concern) {
                headerBtnFollow.setBackgroundResource(R.drawable.comm_btn_gray)
                headerBtnFollow.setTextColor(Color.parseColor("#505050"))
                headerBtnFollow.text = "已关注"
            } else {
                headerBtnFollow.setBackgroundResource(R.drawable.comm_btn_orange)
                headerBtnFollow.setTextColor(Color.parseColor("#FFFFFF"))
                headerBtnFollow.text = "+关注"
            }
        }
    }

    private fun fetchBoardList() {
        if (AppBackgroundInfo.instance.hasLogin) {
            boardViewModel.getBoardList(page, limit, boardUserId, AppBackgroundInfo.instance.userBean!!.userId)
        } else {
            boardViewModel.getBoardList(page, limit, boardUserId, "")
        }
    }
}